<template>
  <div class="admin-dashboard">
    <div class="admin-header">
      <h1>动物乐园后台管理系统</h1>
      <div class="header-actions">
        <span class="welcome-text">欢迎管理员</span>
        <button @click="logout" class="logout-btn">退出登录</button>
      </div>
    </div>
    
    <div class="admin-layout">
      <aside class="sidebar">
        <nav class="admin-nav">
          <ul>
            <li>
              <router-link to="/admin/dashboard" class="nav-item" active-class="active">
                <span class="nav-icon">📊</span>
                <span class="nav-text">仪表盘</span>
              </router-link>
            </li>
            <li>
              <router-link to="/admin/animals" class="nav-item" active-class="active">
                <span class="nav-icon">🐾</span>
                <span class="nav-text">动物管理</span>
              </router-link>
            </li>
            <li>
              <router-link to="/admin/categories" class="nav-item" active-class="active">
                <span class="nav-icon">📂</span>
                <span class="nav-text">分类管理</span>
              </router-link>
            </li>
            <li>
              <router-link to="/admin/users" class="nav-item" active-class="active">
                <span class="nav-icon">👥</span>
                <span class="nav-text">用户管理</span>
              </router-link>
            </li>
          </ul>
        </nav>
      </aside>
      
      <main class="main-content">
        <div class="page-header">
          <h2>用户管理</h2>
        </div>
        
        <div class="search-filter">
          <input 
            v-model="searchQuery" 
            type="text" 
            placeholder="搜索用户名或邮箱..."
            class="search-input"
          />
          <select v-model="selectedRole" class="filter-select">
            <option value="">全部角色</option>
            <option value="user">普通用户</option>
            <option value="admin">管理员</option>
          </select>
          <select v-model="selectedMembership" class="filter-select">
            <option value="">全部会员等级</option>
            <option value="0">非会员</option>
            <option value="1">普通会员</option>
            <option value="2">高级会员</option>
            <option value="3">VIP会员</option>
          </select>
        </div>
        
        <div class="table-container">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>会员等级</th>
                <th>角色</th>
                <th>注册时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in filteredUsers" :key="user.id">
                <td>{{ user.id }}</td>
                <td>
                  <div class="user-info">
                    <div class="user-avatar">{{ user.name.charAt(0).toUpperCase() }}</div>
                    <span>{{ user.name }}</span>
                  </div>
                </td>
                <td>{{ user.email }}</td>
                <td>
                  <span :class="`membership-badge level-${user.membershipLevel}`">
                    {{ getMembershipText(user.membershipLevel) }}
                  </span>
                </td>
                <td>
                  <span :class="`role-badge ${user.role}`">
                    {{ user.role === 'admin' ? '管理员' : '普通用户' }}
                  </span>
                </td>
                <td>{{ formatDate(user.createdAt) }}</td>
                <td>
                  <span :class="`status-badge ${user.status}`">
                    {{ user.status === 'active' ? '活跃' : '禁用' }}
                  </span>
                </td>
                <td>
                  <div class="action-buttons">
                    <button @click="editUser(user)" class="edit-btn">编辑</button>
                    <button 
                      @click="toggleUserStatus(user)" 
                      class="status-btn"
                      :class="user.status === 'active' ? 'deactivate-btn' : 'activate-btn'"
                    >
                      {{ user.status === 'active' ? '禁用' : '启用' }}
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        
        <div class="pagination">
          <button 
            @click="currentPage--" 
            :disabled="currentPage === 1"
            class="pagination-btn"
          >
            上一页
          </button>
          <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
          <button 
            @click="currentPage++" 
            :disabled="currentPage === totalPages"
            class="pagination-btn"
          >
            下一页
          </button>
        </div>
        
        <!-- 编辑用户模态框 -->
        <div v-if="showEditForm" class="modal-overlay" @click="closeModal">
          <div class="modal-content" @click.stop>
            <div class="modal-header">
              <h3>编辑用户</h3>
              <button @click="closeModal" class="close-btn">×</button>
            </div>
            <div class="modal-body">
              <form @submit.prevent="submitForm">
                <div class="form-group">
                  <label for="name">用户名</label>
                  <input 
                    type="text" 
                    id="name" 
                    v-model="formData.name"
                    required
                    class="form-input"
                  />
                </div>
                <div class="form-group">
                  <label for="email">邮箱</label>
                  <input 
                    type="email" 
                    id="email" 
                    v-model="formData.email"
                    required
                    class="form-input"
                  />
                </div>
                <div class="form-group">
                  <label for="role">角色</label>
                  <select 
                    id="role" 
                    v-model="formData.role"
                    class="form-input"
                  >
                    <option value="user">普通用户</option>
                    <option value="admin">管理员</option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="membershipLevel">会员等级</label>
                  <select 
                    id="membershipLevel" 
                    v-model="formData.membershipLevel"
                    class="form-input"
                  >
                    <option value="0">非会员</option>
                    <option value="1">普通会员</option>
                    <option value="2">高级会员</option>
                    <option value="3">VIP会员</option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="status">账户状态</label>
                  <select 
                    id="status" 
                    v-model="formData.status"
                    class="form-input"
                  >
                    <option value="active">活跃</option>
                    <option value="inactive">禁用</option>
                  </select>
                </div>
                <div class="form-actions">
                  <button type="button" @click="closeModal" class="cancel-btn">取消</button>
                  <button type="submit" class="submit-btn">更新</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserManagementView',
  data() {
    return {
      users: [],
      searchQuery: '',
      selectedRole: '',
      selectedMembership: '',
      currentPage: 1,
      itemsPerPage: 10,
      showEditForm: false,
      formData: {
        name: '',
        email: '',
        role: 'user',
        membershipLevel: 0,
        status: 'active'
      },
      editingUserId: null
    }
  },
  computed: {
    filteredUsers() {
      let result = this.users
      
      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(user => 
          user.name.toLowerCase().includes(query) || 
          user.email.toLowerCase().includes(query)
        )
      }
      
      // 角色过滤
      if (this.selectedRole) {
        result = result.filter(user => user.role === this.selectedRole)
      }
      
      // 会员等级过滤
      if (this.selectedMembership !== '') {
        result = result.filter(user => 
          user.membershipLevel === parseInt(this.selectedMembership)
        )
      }
      
      // 分页
      const start = (this.currentPage - 1) * this.itemsPerPage
      const end = start + this.itemsPerPage
      return result.slice(start, end)
    },
    totalPages() {
      let result = this.users
      
      // 应用相同的过滤条件
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(user => 
          user.name.toLowerCase().includes(query) || 
          user.email.toLowerCase().includes(query)
        )
      }
      
      if (this.selectedRole) {
        result = result.filter(user => user.role === this.selectedRole)
      }
      
      if (this.selectedMembership !== '') {
        result = result.filter(user => 
          user.membershipLevel === parseInt(this.selectedMembership)
        )
      }
      
      return Math.ceil(result.length / this.itemsPerPage)
    }
  },
  mounted() {
    this.fetchUsers()
  },
  methods: {
    fetchUsers() {
      // 模拟数据，实际应该从API获取
      this.users = [
        { id: 1, name: '张三', email: 'zhangsan@example.com', membershipLevel: 3, role: 'admin', status: 'active', createdAt: '2023-01-10' },
        { id: 2, name: '李四', email: 'lisi@example.com', membershipLevel: 2, role: 'user', status: 'active', createdAt: '2023-01-15' },
        { id: 3, name: '王五', email: 'wangwu@example.com', membershipLevel: 1, role: 'user', status: 'active', createdAt: '2023-02-01' },
        { id: 4, name: '赵六', email: 'zhaoliu@example.com', membershipLevel: 0, role: 'user', status: 'inactive', createdAt: '2023-02-10' },
        { id: 5, name: '钱七', email: 'qianqi@example.com', membershipLevel: 2, role: 'user', status: 'active', createdAt: '2023-02-20' },
        { id: 6, name: '孙八', email: 'sunba@example.com', membershipLevel: 1, role: 'user', status: 'active', createdAt: '2023-03-05' },
        { id: 7, name: '周九', email: 'zhoujiu@example.com', membershipLevel: 3, role: 'user', status: 'active', createdAt: '2023-03-15' },
        { id: 8, name: '吴十', email: 'wushi@example.com', membershipLevel: 0, role: 'user', status: 'active', createdAt: '2023-03-25' }
      ]
    },
    getMembershipText(level) {
      const levels = ['非会员', '普通会员', '高级会员', 'VIP会员']
      return levels[level] || '未知'
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString()
    },
    editUser(user) {
      this.formData = {
        name: user.name,
        email: user.email,
        role: user.role,
        membershipLevel: user.membershipLevel,
        status: user.status
      }
      this.editingUserId = user.id
      this.showEditForm = true
    },
    toggleUserStatus(user) {
      const newStatus = user.status === 'active' ? 'inactive' : 'active'
      if (confirm(`确定要${newStatus === 'active' ? '启用' : '禁用'}该用户吗？`)) {
        // 实际应该调用API更新状态
        const index = this.users.findIndex(u => u.id === user.id)
        if (index !== -1) {
          this.users[index].status = newStatus
        }
      }
    },
    submitForm() {
      // 编辑模式
      const index = this.users.findIndex(u => u.id === this.editingUserId)
      if (index !== -1) {
        this.users[index] = {
          ...this.users[index],
          ...this.formData
        }
      }
      this.closeModal()
    },
    closeModal() {
      this.showEditForm = false
      this.editingUserId = null
      this.resetForm()
    },
    resetForm() {
      this.formData = {
        name: '',
        email: '',
        role: 'user',
        membershipLevel: 0,
        status: 'active'
      }
    },
    logout() {
      localStorage.removeItem('user')
      this.$router.push('/login')
    }
  }
}
</script>

<style scoped>
/* 复用之前组件的大部分样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.search-filter {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
  flex-wrap: wrap;
}

.search-input,
.filter-select {
  padding: 0.75rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.search-input {
  flex: 1;
  min-width: 200px;
}

.filter-select {
  min-width: 120px;
}

.table-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: bold;
  color: #2c3e50;
}

.data-table tbody tr:hover {
  background-color: #f8f9fa;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #3498db;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 0.9rem;
}

.membership-badge,
.role-badge,
.status-badge {
  padding: 0.25rem 0.75rem;
  border-radius: 1rem;
  font-size: 0.85rem;
  font-weight: 500;
}

.membership-badge.level-0 {
  background-color: #e9ecef;
  color: #495057;
}

.membership-badge.level-1 {
  background-color: #d1ecf1;
  color: #0c5460;
}

.membership-badge.level-2 {
  background-color: #fff3cd;
  color: #856404;
}

.membership-badge.level-3 {
  background-color: #f8d7da;
  color: #721c24;
}

.role-badge.admin {
  background-color: #f8d7da;
  color: #721c24;
}

.role-badge.user {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-badge.active {
  background-color: #d4edda;
  color: #155724;
}

.status-badge.inactive {
  background-color: #e9ecef;
  color: #495057;
}

.action-buttons {
  display: flex;
  gap: 0.5rem;
}

.edit-btn,
.status-btn {
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.edit-btn {
  background-color: #3498db;
  color: white;
}

.edit-btn:hover {
  background-color: #2980b9;
}

.status-btn.deactivate-btn {
  background-color: #e74c3c;
  color: white;
}

.status-btn.deactivate-btn:hover {
  background-color: #c0392b;
}

.status-btn.activate-btn {
  background-color: #27ae60;
  color: white;
}

.status-btn.activate-btn:hover {
  background-color: #229954;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 1.5rem;
}

.pagination-btn {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #f8f9fa;
}

.pagination-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  font-size: 1rem;
  color: #666;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.close-btn:hover {
  background-color: #f8f9fa;
}

.modal-body {
  padding: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #2c3e50;
}

.form-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.form-input:focus {
  outline: none;
  border-color: #3498db;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 2rem;
}

.cancel-btn,
.submit-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
}

.cancel-btn {
  background-color: #6c757d;
  color: white;
}

.cancel-btn:hover {
  background-color: #5a6268;
}

.submit-btn {
  background-color: #28a745;
  color: white;
}

.submit-btn:hover {
  background-color: #218838;
}

@media (max-width: 768px) {
  .search-filter {
    flex-direction: column;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
  }
}
</style>